from shutil import copytree, copy2, ignore_patterns, rmtree, make_archive
import os

common_path = 'common/'
chrome_path = 'chrome/'
chrome_manifest = 'manifest.json'
safari_path = 'safari/xcommander.safariextension/'
safari_manifest = 'Info.plist'
opera_path = 'opera/'
opera_manifest = 'config.xml'

def mycopy(dst, manifest, isSafari):
    errors = []
    names = os.listdir(dst)
    for name in names:
        dstname = os.path.join(dst, name)
        try:
            if os.path.isdir(dstname):
                rmtree(dstname)
            elif name != manifest:
                os.remove(dstname)
        except (IOError, os.error), why:
            errors.append((dstname, str(why)))
        except Error, err:
            errors.extend(err.args[0])

    if isSafari:
        icons_path = os.path.join(common_path, 'icons')
        if os.path.exists(icons_path):
            icons = os.listdir(icons_path)
            for icon in icons:
                if icon.startswith('Icon', 0,4):
                    srcicon = os.path.join(icons_path, icon)
                    dsticon = os.path.join(dst, icon)
                    try:
                        copy2(srcicon, dsticon)
                    except (IOError, os.error), why:
                        errors.append((srcicon, dsticon, str(why)))
                    except Error, err:
                        errors.extend(err.args[0])
                        
    names = os.listdir(common_path)
    for name in names:
        srcname = os.path.join(common_path, name)
        dstname = os.path.join(dst, name)
        try:
            if os.path.isdir(srcname):
                copytree(srcname, dstname)
            else:
                copy2(srcname, dstname)
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        except Error, err:
            errors.extend(err.args[0])


if os.path.exists(common_path):
    if os.path.exists('extensions/xcommander.oex'):
        os.remove('extensions/xcommander.oex')
    # create chrome extension
    mycopy(chrome_path, chrome_manifest, False)
    # create safari extension
    mycopy(safari_path, safari_manifest, True)
    # create opera extension
    mycopy(opera_path, opera_manifest, False)
    make_archive('xcommander', 'zip', opera_path)
    os.rename('xcommander.zip', 'extensions/xcommander.oex')



